// File: dao/ChapterDao.cpp
#include "chapterdao.h"

ChapterDao::ChapterDao(QObject *parent) : QObject(parent) {}

//新增
bool ChapterDao::insert(ChapterInfo *chapter) {
    QSqlQuery query;

    // 修正后的插入sql
    QString sql = "INSERT INTO chapter_info (id, title, novel_id, chapter_index, path, word_count, start_offset, end_offset, prev_chapter, next_chapter, load_status, status) "
                  "VALUES (:id, :title, :novel_id, :chapter_index, :path, :word_count, :start_offset, :end_offset, :prev_chapter, :next_chapter, :load_status, :status);";

    query.prepare(sql);
    qDebug() << "Prepared SQL statement:" << sql;

    // 绑定数值
    query.bindValue(":id", chapter->getId());
    query.bindValue(":title", chapter->getTitle());
    query.bindValue(":novel_id", chapter->getNovelId());
    query.bindValue(":chapter_index", chapter->getChapterIndex());
    query.bindValue(":path", chapter->getPath());
    query.bindValue(":word_count", chapter->getWordCount());
    query.bindValue(":start_offset", chapter->getStartOffset());
    query.bindValue(":end_offset", chapter->getEndOffset());
    query.bindValue(":prev_chapter", chapter->getPrevChapter());
    query.bindValue(":next_chapter", chapter->getNextChapter());
    query.bindValue(":load_status", chapter->getLoadStatus());
    query.bindValue(":status", chapter->getStatus());

    // 执行插入
    if (query.exec()) {
        qDebug() << "插入章节信息成功：" << query.lastInsertId();
        return true;
    } else {
        qDebug() << "插入章节信息失败，信息:" << query.lastError().text();
        qDebug() << "失败语句:" << query.lastQuery();
        return false;
    }
}

//批量新增
bool ChapterDao::batchInsert(QVector<ChapterInfo*>& chapterList) {
    if (chapterList.isEmpty()) {
        qDebug() << "批量插入失败：章节列表为空";
        return false;
    }

    QSqlDatabase db = QSqlDatabase::database();
    if (!db.isOpen()) {
        qDebug() << "批量插入失败：数据库未打开";
        return false;
    }

    // 开启事务
    db.transaction();

    QSqlQuery query;
    QString sql = "INSERT INTO chapter_info (id, title, novel_id, chapter_index, path, word_count, start_offset, end_offset, prev_chapter, next_chapter, load_status, status) "
                  "VALUES (:id, :title, :novel_id, :chapter_index, :path, :word_count, :start_offset, :end_offset, :prev_chapter, :next_chapter, :load_status, :status)";

    query.prepare(sql);

    // 循环处理每个章节
    for (ChapterInfo* chapter : chapterList) {
        if (!chapter) continue; // 跳过空指针

        // 绑定数值
        query.bindValue(":id", chapter->getId());
        query.bindValue(":title", chapter->getTitle());
        query.bindValue(":novel_id", chapter->getNovelId());
        query.bindValue(":chapter_index", chapter->getChapterIndex());
        query.bindValue(":path", chapter->getPath());
        query.bindValue(":word_count", chapter->getWordCount());
        query.bindValue(":start_offset", chapter->getStartOffset());
        query.bindValue(":end_offset", chapter->getEndOffset());
        query.bindValue(":prev_chapter", chapter->getPrevChapter());
        query.bindValue(":next_chapter", chapter->getNextChapter());
        query.bindValue(":load_status", chapter->getLoadStatus());
        query.bindValue(":status", chapter->getStatus());

        // 执行插入
        if (!query.exec()) {
            qDebug() << "批量插入失败，章节ID:" << chapter->getId() << "，错误信息:" << query.lastError().text();
            db.rollback(); // 回滚事务
            return false;
        }
    }

    // 提交事务
    if (db.commit()) {
        qDebug() << "批量插入成功，共插入" << chapterList.size() << "个章节";
        return true;
    } else {
        qDebug() << "批量插入失败：事务提交失败" << db.lastError().text();
        return false;
    }

}

bool ChapterDao::deleteByNovelId(const QString &novelId)
{
    QSqlQuery query;
    query.prepare("DELETE FROM chapter_info WHERE novel_id = :novel_id");
    query.bindValue(":novel_id", novelId);

    if (!query.exec()) {
        qWarning() << "Delete chapters failed:" << query.lastError().text();
        return false;
    }

    return true;
}

ChapterInfo* ChapterDao::getById(const QString &chapterId)
{
    QSqlQuery query;
    query.prepare("SELECT * FROM chapter_info WHERE id = :id");
    query.bindValue(":id", chapterId);

    if (!query.exec() || !query.next()) {
        return nullptr;
    }

    ChapterInfo *chapter = new ChapterInfo();

    // 映射id（字符串类型）
    chapter->setId(query.value("id").toString());
    // 映射所属小说id
    chapter->setNovelId(query.value("novel_id").toString());
    // 映射章节标题
    chapter->setTitle(query.value("title").toString());
    // 映射章节索引（int类型）
    chapter->setChapterIndex(query.value("chapter_index").toInt());
    // 映射章节路径
    chapter->setPath(query.value("path").toString());
    // 映射章节字数
    chapter->setWordCount(query.value("word_count").toInt());
    // 映射开始偏移量
    chapter->setStartOffset(query.value("start_offset").toInt());
    // 映射结束偏移量
    chapter->setEndOffset(query.value("end_offset").toInt());
    // 映射上一章节id
    chapter->setPrevChapter(query.value("prev_chapter").toString());
    // 映射下一章节id
    chapter->setNextChapter(query.value("next_chapter").toString());
    // 映射加载状态
    chapter->setLoadStatus(query.value("load_status").toInt());
    // 映射阅读状态（0未读，1阅读中，2阅读完）
    chapter->setStatus(query.value("status").toInt());

    return chapter;
}

QList<QObject*> ChapterDao::getByNovelId(const QString &novelId)
{
    QList<QObject*> chapters;
    QSqlQuery query;
    query.prepare("SELECT * FROM chapter_info WHERE novel_id = :novel_id ORDER BY chapter_index");
    query.bindValue(":novel_id", novelId);

    if (!query.exec()) {
        qDebug() << "小说:"<< novelId <<",章节查询失败！"
         << "错误信息:" << query.lastError().text();
        return chapters;
    }

    qDebug() << "章节数：" << chapters.size();

    while (query.next()) {
        ChapterInfo *chapter = new ChapterInfo();

         // 映射id（字符串类型）
         chapter->setId(query.value("id").toString());
         // 映射所属小说id
         chapter->setNovelId(query.value("novel_id").toString());
         // 映射章节标题
         chapter->setTitle(query.value("title").toString());
         // 映射章节索引（int类型）
         chapter->setChapterIndex(query.value("chapter_index").toInt());
         // 映射章节路径
         chapter->setPath(query.value("path").toString());
         // 映射章节字数
         chapter->setWordCount(query.value("word_count").toInt());
         // 映射开始偏移量
         chapter->setStartOffset(query.value("start_offset").toInt());
         // 映射结束偏移量
         chapter->setEndOffset(query.value("end_offset").toInt());
         // 映射上一章节id
         chapter->setPrevChapter(query.value("prev_chapter").toString());
         // 映射下一章节id
         chapter->setNextChapter(query.value("next_chapter").toString());
         // 映射加载状态
         chapter->setLoadStatus(query.value("load_status").toInt());
         // 映射阅读状态（0未读，1阅读中，2阅读完）
         chapter->setStatus(query.value("status").toInt());

         qDebug() << "=====>章节信息：" << chapter->toString();

         chapters.append(chapter);
    }

    return chapters;
}

QList<ChapterInfo*> ChapterDao::getByRange(const QString &novelId, int startIndex, int count)
{
    QList<ChapterInfo*> chapters;
    QSqlQuery query;
    query.prepare("SELECT * FROM chapter_info WHERE novel_id = :novel_id "
                  "ORDER BY order_index LIMIT :count OFFSET :offset");
    query.bindValue(":novel_id", novelId);
    query.bindValue(":count", count);
    query.bindValue(":offset", startIndex);

    if (!query.exec()) {
        return chapters;
    }

    while (query.next()) {
        ChapterInfo *chapter = new ChapterInfo();

        // 映射id（字符串类型）
        chapter->setId(query.value("id").toString());
        // 映射所属小说id
        chapter->setNovelId(query.value("novel_id").toString());
        // 映射章节标题
        chapter->setTitle(query.value("title").toString());
        // 映射章节索引（int类型）
        chapter->setChapterIndex(query.value("chapter_index").toInt());
        // 映射章节路径
        chapter->setPath(query.value("path").toString());
        // 映射章节字数
        chapter->setWordCount(query.value("word_count").toInt());
        // 映射开始偏移量
        chapter->setStartOffset(query.value("start_offset").toInt());
        // 映射结束偏移量
        chapter->setEndOffset(query.value("end_offset").toInt());
        // 映射上一章节id
        chapter->setPrevChapter(query.value("prev_chapter").toString());
        // 映射下一章节id
        chapter->setNextChapter(query.value("next_chapter").toString());
        // 映射加载状态
        chapter->setLoadStatus(query.value("load_status").toInt());
        // 映射阅读状态（0未读，1阅读中，2阅读完）
        chapter->setStatus(query.value("status").toInt());

        chapters.append(chapter);
    }

    return chapters;
}

//更新章节
bool ChapterDao::update(ChapterInfo *chapter) {
    if (!chapter) {
            qDebug() << "更新失败：章节对象为空";
            return false;
        }

        QSqlQuery query;
        QString sql = "UPDATE chapter_info "
                      "SET title = :title, "
                      "    novel_id = :novel_id, "
                      "    chapter_index = :chapter_index, "
                      "    path = :path, "
                      "    word_count = :word_count, "
                      "    start_offset = :start_offset, "
                      "    end_offset = :end_offset, "
                      "    prev_chapter = :prev_chapter, "
                      "    next_chapter = :next_chapter, "
                      "    load_status = :load_status, "
                      "    status = :status "
                      "WHERE id = :id";

        query.prepare(sql);

        // 绑定要更新的值
        query.bindValue(":title", chapter->getTitle());
        query.bindValue(":novel_id", chapter->getNovelId());
        query.bindValue(":chapter_index", chapter->getChapterIndex());
        query.bindValue(":path", chapter->getPath());
        query.bindValue(":word_count", chapter->getWordCount());
        query.bindValue(":start_offset", chapter->getStartOffset());
        query.bindValue(":end_offset", chapter->getEndOffset());
        query.bindValue(":prev_chapter", chapter->getPrevChapter());
        query.bindValue(":next_chapter", chapter->getNextChapter());
        query.bindValue(":load_status", chapter->getLoadStatus());
        query.bindValue(":status", chapter->getStatus());

        // 设置 WHERE 子句中的 ID
        query.bindValue(":id", chapter->getId());

        // 执行更新
        if (query.exec()) {
            // 检查是否有行受到影响
            if (query.numRowsAffected() > 0) {
                qDebug() << "更新章节信息成功，ID:" << chapter->getId();
                return true;
            } else {
                qDebug() << "更新失败：未找到ID为" << chapter->getId() << "的章节";
                return false;
            }
        } else {
            qDebug() << "更新章节信息失败，错误信息:" << query.lastError().text();
            qDebug() << "失败语句:" << query.lastQuery();
            return false;
        }
}

//根据小说id与索引查询章节
ChapterInfo* ChapterDao::queryOne(const QString &novelId, int index) {
    QSqlQuery query;
    QString sql = "SELECT * FROM chapter_info "
                  "WHERE novel_id = :novel_id AND chapter_index = :chapter_index";

    query.prepare(sql);
    query.bindValue(":novel_id", novelId);
    query.bindValue(":chapter_index", index);

    if (query.exec() && query.next()) {
        ChapterInfo* chapter = new ChapterInfo();

        // 从结果集填充实体对象
        chapter->setId(query.value("id").toString());
        chapter->setTitle(query.value("title").toString());
        chapter->setNovelId(query.value("novel_id").toString());
        chapter->setChapterIndex(query.value("chapter_index").toInt());
        chapter->setPath(query.value("path").toString());
        chapter->setWordCount(query.value("word_count").toInt());
        chapter->setStartOffset(query.value("start_offset").toLongLong());
        chapter->setEndOffset(query.value("end_offset").toLongLong());
        chapter->setPrevChapter(query.value("prev_chapter").toString());
        chapter->setNextChapter(query.value("next_chapter").toString());
        chapter->setLoadStatus(query.value("load_status").toInt());
        chapter->setStatus(query.value("status").toInt());

        qDebug() << "查询章节成功，ID:" << chapter->getId()
                 << "，标题:" << chapter->getTitle();

        return chapter;
    } else {
        qDebug() << "未找到章节，novel_id:" << novelId
                 << "，chapter_index:" << index;
        return nullptr;
    }
}


bool ChapterDao::updateContentPath(const QString &chapterId, const QString &contentPath)
{
    QSqlQuery query;
    query.prepare("UPDATE chapter_info SET path = :content_path WHERE id = :id");
    query.bindValue(":content_path", contentPath);
    query.bindValue(":id", chapterId);

    if (!query.exec()) {
        qWarning() << "ChapterDao::updateChapterContentPath - Error:" << query.lastError().text();
        return false;
    }
    return true;
}
